package com.maogouxiong.seatatestorder.order.config;

/**
 * @ClassName DataSourceProxyConfig
 * @Description
 * @Author zhanhao
 * @Date 2020/6/18 10:49
 * @Version V1.0
 **/

import com.alibaba.druid.pool.DruidDataSource;
import io.seata.rm.datasource.DataSourceProxy;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.transaction.SpringManagedTransactionFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * 使用Seata对数据源进行代理
 * Created by macro on 2019/11/11.
 */
@Configuration
public class DataSourceConfig {

    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setPassword("123456");
        dataSource.setUsername("root");
        dataSource.setUrl("jdbc:mysql://localhost:3306/seata_order?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8");
        dataSource.setMaxActive(2000);
        dataSource.setMaxWait(20000);
        return dataSource;
    }

    //创建了DataSourceProxy，并把它设置到Mybatis中的SqlSessionFactory。
    //我们知道，在Mybatis执行方法的时候，最终要创建PreparedStatement对象，然后执行ps.execute()返回SQL结果。
    @Bean
    public DataSourceProxy dataSourceProxy() throws SQLException {
        return new DataSourceProxy(dataSource());
    }

    @Bean
    public SqlSessionFactory sqlSessionFactoryBean() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSourceProxy());
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));
        sqlSessionFactoryBean.setTransactionFactory(new SpringManagedTransactionFactory());
        return sqlSessionFactoryBean.getObject();
    }
}
